import moment from "moment";
import React, { useEffect, useState } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import Breadcrumb from "../components/Breadcrumb";
import Footer from "../components/Footer";
import Header from "../components/Header";
import service from "../service";

export default function NewsDetails() {
  //非状态变量 —— 面包屑路径，不需要进行数据响应式
  const path = [
    { name: "首页", href: "/" },
    { name: "新闻列表", href: "/news" },
    { name: "新闻详情", href: "/news_details" },
  ];
  let [news, setNews] = useState({});
  let [params, setParams] = useSearchParams(); //从路由参数（查询字符串）中读取上一页传递来的“新闻编号”
  // 钩子必须在组件顶层调用 不允许在if/回调方法
  let nid = params.get("nid");
  let nav = useNavigate();
  //组件挂载时，根据上一页传递的路由参数（nid）异步请求指定新闻的详情
  useEffect(function () {
    service
      .newsDetail(nid)
      .then((data) => {
        console.log(data);
        setNews(data);
      })
      .catch((err) => console.log(err));
  }, []);
  if (!nid) {
    nav("/news");
    return;
  }
  return (
    <>
      {/* header */}
      <div className="header_box">
        <Header></Header>
      </div>
      {/* breadcrumb */}
      <Breadcrumb path={path}></Breadcrumb>
      {/* main */}
      <div className="main container">
        <div className="news_details">
          <h2>{news.title}</h2>
          <span>
            发布时间：{moment(Number(news.pubTime)).format("YY-MM-DD HH:mm:ss")}
          </span>
          <div
            dangerouslySetInnerHTML={{ __html: news.content }}
            className="news_content"
          ></div>
        </div>
      </div>
      {/* footer */}
      <footer className="footer">
        <Footer></Footer>
      </footer>
    </>
  );
}
